<template>
  <div class="login-container">
    <div class="login-card">
      <div class="logo">
        <i class="fas fa-lock"></i>
      </div>
      <h1>欢迎注册</h1>
      <form @submit.prevent="register">
        <div class="input-group">
          <i class="fas fa-user"></i>
          <input v-model="username" type="text" placeholder="请输入账号" required />
        </div>
        <div class="input-group">
          <i class="fas fa-user"></i>
          <input v-model="truename" type="text" placeholder="请输入真实姓名" required />
        </div>
        <div class="input-group">
          <i class="fas fa-envelope"></i>
          <input v-model="email" type="email" placeholder="请输入电子邮箱" required />
        </div>
        <div class="input-group">
          <i class="fas fa-key"></i>
          <input v-model="password" type="password" placeholder="请输入密码" required />
        </div>
        <div class="input-group">
          <i class="fas fa-check-circle"></i>
          <input v-model="confirmPassword" type="password" placeholder="确认密码" required />
        </div>
        <button type="submit" class="login-btn">注 册</button>
        <p class="signup">
          已有账号？<router-link to="/login">返回登录</router-link>
        </p>
      </form>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
const username = ref('')
const truename = ref('')
const email = ref('')
const password = ref('')
const confirmPassword = ref('')
const router = useRouter()

function downloadAccountInfo(username, password) {
  const content = `真实姓名: ${truename}\n邮箱：${email}\n账号：${username}\n密码：${password}\n请妥善保管！`
  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = '您的账号密码信息.txt'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}



async function register() {
  if (password.value !== confirmPassword.value) {
    alert('两次密码不一致！')
    return
  }
  try {
    const res = await axios.post('http://localhost:8080/api/users/register', {
      username: username.value,
      truename: truename.value,
      email: email.value,
      password: password.value
    })
    downloadAccountInfo(username.value, password.value)
    alert('注册成功！')
    router.push('/login')
  } catch (err) {
    alert('注册失败：' + (err.response?.data || '网络错误'))
  }
}
</script>

<style scoped>
/* 复用 style.css  */
</style>